AddCSLuaFile( "cl_init.lua" );
AddCSLuaFile( "shared.lua" );

include( "shared.lua" );

ENT.Spawnable = true;

function ENT:SpawnFunction( ply, tr )

	if( !tr.Hit ) then return end
	
	local pos = tr.HitPos + tr.HitNormal * 16;
	
	local ent = ents.Create( self.ClassName );
	ent:SetPos( pos );
	ent:Spawn();
	ent:Activate();
	
	return ent;
	
end

function ENT:Initialize()
	
	self:SetModel( "models/props_lab/tpplugholder_single.mdl" );
	self:PhysicsInit( SOLID_VPHYSICS );
	self:SetMoveType( MOVETYPE_VPHYSICS );
	self:SetSolid( SOLID_VPHYSICS );
	
	local phys = self:GetPhysicsObject();
	if( phys and phys:IsValid() ) then
		
		phys:Wake();
		
	end
	
	self:SetUseType( SIMPLE_USE );
	
	C.ClearLinks( self );
	
end

function ENT:Use( act, call, type, val )
	
	local cont = self:GetAnyContainer();
	
	if( cont and cont:IsValid() ) then
		
		for _, v in pairs( self.Links ) do
			
			if( v.CosmicType == CE_TERMINAL ) then
				
				for _, n in pairs( v.Links ) do
					
					if( n.CosmicType == CE_CONTAINER ) then
						
						for k, l in pairs( self.Resources ) do
							
							self:SapResources( cont, n, k );
							
						end
						
					end
					
				end
				
			end
			
		end
		
	end
	
end

function ENT:SapResources( targ, dest, res ) -- Container to put, sapping from, resource type
	
	local o = dest:GetAmount( res );
	local m = targ:GetMax( res );
	local c = targ:GetAmount( res );
	
	local maxFrom = m - c;
	
	if( maxFrom > 0 ) then
		
		local toTrans = math.min( maxFrom, o );
		
		targ:AddResource( res, toTrans );
		dest:SetAmount( res, o - toTrans );
		
	end
	
end

function ENT:CheckLinks()
	
	for k, v in pairs( self.Links ) do
		
		if( !v or !v:IsValid() ) then
			
			table.remove( self.Links, k );
			continue;
			
		end
		
		if( v:GetPos():Distance( self:GetPos() ) > 1024 ) then
			
			table.remove( self.Links, k );
			
			self:EmitSound( Sound( "weapons/stunstick/spark" .. tostring( math.random( 1, 3 ) ) .. ".wav" ) );
			
		end
		
	end
	
end

function ENT:AccessResource( res, amt )
	
	for _, v in pairs( self.Links ) do
		
		if( v.CosmicType == CE_CONTAINER and v:GetAmount( res ) >= amt ) then
			
			return true;
			
		end
		
	end
	
	return false;
	
end

function ENT:GetContainer( res, amt )
	
	for _, v in pairs( self.Links ) do
		
		if( v.CosmicType == CE_CONTAINER and v:GetAmount( res ) > amt ) then
			
			return v;
			
		end
		
	end
	
end

function ENT:GetAnyContainer()
	
	for _, v in pairs( self.Links ) do
		
		if( v.CosmicType == CE_CONTAINER ) then
			
			return v;
			
		end
		
	end
	
end

function ENT:Think()
	
	self:CheckLinks();
	
end